package Downloader

import (
	"fmt"
	"sync/atomic"
	"time"
)

type Speed struct {
	newNByts int64
	oldNByts int64
	deltTime time.Duration
}

func NewSpeed() (r *Speed) {
	r = new(Speed)
	r.newNByts = 0
	r.oldNByts = 0
	r.deltTime = time.Second * 3
	return
}

func (this *Speed) loadNewByts() (r int64) {
	r = atomic.LoadInt64(&this.newNByts)
	return
}

func (this *Speed) loadOldByts() (r int64) {
	r = atomic.LoadInt64(&this.oldNByts)
	return
}

func (this *Speed) showSpeed() {
	newNByts := this.loadNewByts()
	oldNByts := this.loadOldByts()
	speed := float64(newNByts-oldNByts) / float64(this.deltTime) * 1.0e9
	atomic.SwapInt64(&this.oldNByts, this.newNByts) //equals oldNByts=newNByts
	fmt.Printf("Average Speed %.1fKB\n", speed/1000)
}

func (this *Speed) startTimer() {
	ch := make(chan byte)
	go func(c chan byte) {
		select {
		case <-time.After(this.deltTime):
			this.showSpeed()
			close(ch)
			go this.startTimer()
		case <-ch:
		}
	}(ch)
}

func (this *Speed) Increase(nBytes int) {
	atomic.AddInt64(&this.newNByts, int64(nBytes))
}

func (this *Speed) AutomaticallyShow() {
	go this.startTimer()
}
